
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using log4net;

namespace mojoPortal.Web.Framework
{
    public static class XmlHelper
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(XmlHelper));

        public static void AddNode(XmlDocument xmlDoc, string name, string content)
        {
            XmlElement elem = xmlDoc.CreateElement(name);
            XmlText text = xmlDoc.CreateTextNode(content);
            xmlDoc.DocumentElement.AppendChild(elem);
            xmlDoc.DocumentElement.LastChild.AppendChild(text);
           
        }

        /// <summary>
        /// transforms xml from a given url using xsl from a given url
        /// returns an empty string and logs an error if an error occurs
        /// </summary>
        /// <param name="xmlUrl"></param>
        /// <param name="xslUrl"></param>
        /// <returns></returns>
        public static string TransformXML(string xmlUrl, string xslUrl)
        {
            if (string.IsNullOrEmpty(xmlUrl)) { throw new ArgumentException("xmlUrl is required"); }
            if (string.IsNullOrEmpty(xslUrl)) { throw new ArgumentException("xslUrl is required"); }
            
            StringWriter stringWriter = new StringWriter();
            try
            {
                XmlTextReader xmlReader = new XmlTextReader(xmlUrl);
                XslCompiledTransform xslTransform = new XslCompiledTransform();
                xslTransform.Load(xslUrl);

                XPathDocument xPathDocument = new XPathDocument(xmlReader);

                xslTransform.Transform(xPathDocument, null, stringWriter);
                return stringWriter.ToString();
            }
            catch (XsltCompileException ex) 
            {
                log.Info("swallowed exception for xml path " + xmlUrl + " and xsl path " + xslUrl, ex);
            }
            catch (System.Security.SecurityException ex)
            {
                log.Info("swallowed exception for xml path " + xmlUrl + " and xsl path " + xslUrl, ex);
            }

            return string.Empty;
            
        }


    }
}
